﻿using B.Auth.APi.Application.Command.Role;
using B.Auth.Domain.Entity;
using B.Auth.Domain.Repository;
using B.Auth.Enum;
using MediatR;
using System.Diagnostics;

namespace B.Auth.APi.Application.CommandHand.Role
{
    public class AddRoleUserCommandHand : IRequestHandler<AddRoleUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleUser> db;

        public AddRoleUserCommandHand(IBaseRepository<RoleUser> db)
        {
            this.db = db;
        }

        public Task<ApiResult<int>> Handle(AddRoleUserCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

           List<int> userall=request.UserId.Split(',').Select(p=>Convert.ToInt32(p)).ToList();


            foreach (var item in userall)
            {

                var role = db.GetAll().FirstOrDefault(x => x.RoleId == request.RoleId);
                if (role != null)
                {

                    db.Delect(role);

                }
            }



            foreach (var item in userall)
            {
               

                RoleUser roleUser = new RoleUser()
                {

                    UserId = item,
                    RoleId=request.RoleId,

                };
              
                    result.data += db.Addlist(roleUser);

            }

            result.Message = "添加成功";
            result.Code = ApiEnum.ok;
            return Task.FromResult(result);
        }
    }
}
